import 'dart:async';
import 'food.dart';
import 'snake.dart';

class GameController {
  final int gridSize;
  late Snake snake;
  late Food food;
  int score = 0;
  bool isGameOver = false;
  bool isPaused = false;
  int speed = 200; // 毫秒
  
  late Timer _gameTimer;
  final Function() onUpdate;
  
  GameController(this.gridSize, this.onUpdate) {
    reset();
  }
  
  void reset() {
    snake = Snake();
    food = Food(gridSize);
    food.reset(snake.body);
    score = 0;
    isGameOver = false;
    isPaused = false;
  }
  
  void start() {
    _gameTimer = Timer.periodic(Duration(milliseconds: speed), (timer) {
      if (!isPaused && !isGameOver) {
        _update();
        onUpdate();
      }
    });
  }
  
  void _update() {
    snake.move();
    
    // 检查是否吃到食物
    if (snake.body.first.x == food.position.x && 
        snake.body.first.y == food.position.y) {
      snake.grow();
      score++;
      food.reset(snake.body);
    }
    
    // 检查碰撞
    if (_checkWallCollision() || snake.checkSelfCollision()) {
      isGameOver = true;
      _gameTimer.cancel();
    }
  }
  
  bool _checkWallCollision() {
    final head = snake.body.first;
    return head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize;
  }
  
  void pause() {
    isPaused = true;
  }
  
  void resume() {
    isPaused = false;
  }
  
  void changeSpeed(int newSpeed) {
    speed = newSpeed;
    if (!isGameOver) {
      _gameTimer.cancel();
      start();
    }
  }
  
  void dispose() {
    _gameTimer.cancel();
  }
}